var datasets={};
var plots={};
var options;
var plot;

var datasets2={};
var options2;
var plots2={};


var datasets3={};
var options3;
var plots3={};

function loadPage(){
	
	$("#content").hide();
	//timestamp are using client gmt
	options = {
			series: { shadowSize: 0},
			legend:{
		       show:false
	        },
	        crosshair: { mode: "x" },
            grid: { hoverable: true, autoHighlight: false },
	        xaxis: {  tickFormatter: function(val){ 
		         var d = new Date(val); 
		         return getDay(d) + "/" +getMonth(d)+" "+ getHour(d)+":"+getMinute(d); 
	        }}
	  };
	
	 options2 = {
					series: {
						lines: { show: true, fill: true },
						points: { show: false }
					},
					legend:{
					       show:false
				    },    
					grid: { hoverable: true, autoHighlight: false },
			        xaxis: {  tickFormatter: function(val){ 
				         var d = new Date(val); 
				         return getDay(d) + "/" +getMonth(d)+" "+ getHour(d)+":"+getMinute(d); 
			        }}
	  };
	 
	 options3 = {
				series: {
					lines: { show: true, fill: false },
					points: { show: false }
				},	
				legend:{
				       show:false
			    },
				grid: { hoverable: true, autoHighlight: false },
		        xaxis: {  tickFormatter: function(val){ 
			         var d = new Date(val); 
			         return getDay(d) + "/" +getMonth(d)+" "+ getHour(d)+":"+getMinute(d); 
		        }}
	 };
	
	 
	 jQuery.ajax( {
			type : "GET",
			url : "load_main",
			dataType : "json",
			async : true,
			success : function(json) {
			
		 	  $("#footer").html(parseTemplate("graph_right", {
					json : json["data"]
			  }));
		 	  
		 	  drawMemoryUsage(json);
		      
		      drawMemoryDetail(json);
		      
		      drawCPUUsage(json);
		      
			}
		});
	 update();
}

function drawCPUUsage(json){
	for(prop in json["data"]){
		 var i = 0;//prevent shifting color
	      $.each(json["data"][prop]["dataset3"], function(key, val) {
	          val.color = i;
	          ++i;
	      });
	      datasets3[prop]=json["data"][prop]["dataset3"];
	      
	}
	
	var plot;
	  for(prop in datasets3){
		  var datas=datasets3[prop];
		  var data=[];
		  for(key in datas){
			  data.push(datas[key]);
		  }
		  plot=$.plot($("#cpuUsage_"+prop),data , options3);
		  plots3[""+prop]=plot;

//		  $("#placeholder_"+prop).bind("plothover",{ param: plots[""+prop],param2: prop }, function (event, pos, item) {
//		      latestPosition = pos;
//		      latestPlot=event.data.param;
//		      latestInstaneId=event.data.param2;
//		      if (!updateLegendTimeout)
//		          updateLegendTimeout = setTimeout(memoryDetailCrossHair, 50);
//		  });
		 
		  
//		  $("#placeholder_"+prop).mouseout({param: prop },function(event){
//		      clearEachItemValue(event.data.param);
//		  });
		  
	  }
	  
}


function drawMemoryUsage(json){
	for(prop in json["data"]){
		 var i = 0;//prevent shifting color
	      $.each(json["data"][prop]["dataset2"], function(key, val) {
	          val.color = i;
	          ++i;
	      });
	      datasets2[prop]=json["data"][prop]["dataset2"];
	      
	}
	
	var plot;
	  for(prop in datasets2){
		  var datas=datasets2[prop];
		  var data=[];
		  for(key in datas){
			  data.push(datas[key]);
		  }
		  plot=$.plot($("#memoryUsage_"+prop),data , options2);
		  plots2[""+prop]=plot;

//		  $("#placeholder_"+prop).bind("plothover",{ param: plots[""+prop],param2: prop }, function (event, pos, item) {
//		      latestPosition = pos;
//		      latestPlot=event.data.param;
//		      latestInstaneId=event.data.param2;
//		      if (!updateLegendTimeout)
//		          updateLegendTimeout = setTimeout(memoryDetailCrossHair, 50);
//		  });
		 
		  
//		  $("#placeholder_"+prop).mouseout({param: prop },function(event){
//		      clearEachItemValue(event.data.param);
//		  });
		  
	  }
	  
}

var updateLegendTimeout = null;
var latestPosition = null;
var latestPlot=null;
var latestInstaneId;
function drawMemoryDetail(json) {
	
	    for(prop in json["data"]){
	  	  var i = 0;//prevent shifting color
		      $.each(json["data"][prop]["dataset"], function(key, val) {
		          val.color = i;
		          ++i;
		      });
		      datasets[prop]=json["data"][prop]["dataset"];
		      
		      jQuery("#codeCache_"+prop).bind("click", { param: prop },legendItemClick);
		      
		      jQuery("#codeCachem_"+prop).bind("click", { param: prop },legendItemClick);
		  	
			  jQuery("#edenSpace_"+prop).bind("click", { param: prop },legendItemClick);
			  	
			  jQuery("#edenSpacem_"+prop).bind("click", { param: prop },legendItemClick);
			  	
			  jQuery("#survivorSpace_"+prop).bind("click", { param: prop },legendItemClick);
			  	
			  jQuery("#survivorSpacem_"+prop).bind("click", { param: prop },legendItemClick);
			  	
			  jQuery("#oldGenSpace_"+prop).bind("click", { param: prop },legendItemClick);
			  	
			  jQuery("#oldGenSpacem_"+prop).bind("click", { param: prop },legendItemClick);
			  	
			  jQuery("#permGenSpace_"+prop).bind("click", { param: prop },legendItemClick);
			  
			  jQuery("#permGenSpacem_"+prop).bind("click", { param: prop},legendItemClick);
		  		
	    }
	    
	  var plot;
	  for(prop in datasets){
		  var datas=datasets[prop];
		  var data=[];
		  for(key in datas){
			  data.push(datas[key]);
		  }
		  plot=$.plot($("#placeholder_"+prop),data , options);
		  plots[""+prop]=plot;

		  $("#placeholder_"+prop).bind("plothover",{ param: plots[""+prop],param2: prop }, function (event, pos, item) {
		      latestPosition = pos;
		      latestPlot=event.data.param;
		      latestInstaneId=event.data.param2;
		      if (!updateLegendTimeout)
		          updateLegendTimeout = setTimeout(memoryDetailCrossHair, 50);
		  });
		 
		  
		  $("#placeholder_"+prop).mouseout({param: prop },function(event){
		      clearEachItemValue(event.data.param);
		  });
		  
	  }
     
}

function update() {
	
	 jQuery.ajax( {
			type : "GET",
			url : "load_main",
			dataType : "json",
			async : true,
			success : function(json) {
		 
		 	 updateMemoryUsage(json);
		     updateMemoryDetail(json);
		     updateCpuUsage(json);
		
		}
		});
    
    setTimeout(update,10000);
}

function updateCpuUsage(json){
	
	 var plot;
	 for(prop in json["data"]){

		 var i=0;
		 $.each(json["data"][prop]["dataset3"], function(key, val) {
			 val.color = i;
			 ++i;
		 });
		  var datas=datasets3[prop]=json["data"][prop]["dataset3"];
	      var data=[];
	      for(key in datas){
			  data.push(datas[key]);
		  }
		  plot=plots3[""+prop];
		  plot.setData(data);
		  plot.setupGrid();
	      plot.draw();
		   //$.plot($("#placeholder_"+prop),data , options);
	 }
	
}

function updateMemoryUsage(json){
	
	 var plot;
	 for(prop in json["data"]){
 
		 var i=0;
		 $.each(json["data"][prop]["dataset2"], function(key, val) {
			 val.color = i;
			 ++i;
		 });
		  var datas=datasets2[prop]=json["data"][prop]["dataset2"];
	      var data=[];
	      for(key in datas){
			  data.push(datas[key]);
		  }
		  plot=plots2[""+prop];
		  plot.setData(data);
		  plot.setupGrid();
	      plot.draw();
		   //$.plot($("#placeholder_"+prop),data , options);
	 }
	
}

function updateMemoryDetail(json){
	
	 var plot;
	 for(prop in json["data"]){
  
		 var i=0;
		 $.each(json["data"][prop]["dataset"], function(key, val) {
			 val.color = i;
			 ++i;
		 });
		  var datas=datasets[prop]=json["data"][prop]["dataset"];
	      var data=[];
		  var choiceContainer = $("#legend2333_"+prop);
		    choiceContainer.find("input:checked").each(function () {
		        var key = $(this).attr("name");
		        if (key && datas[key])
		            data.push(datas[key]);
		    });
		    plot=plots[""+prop];
		    plot.setData(data);
		    plot.setupGrid();
	        plot.draw();
		   //$.plot($("#placeholder_"+prop),data , options);
	 }
	
}

function memoryDetailCrossHair() {
	
    updateLegendTimeout = null;
    
    var pos = latestPosition;
    var plot=latestPlot;
    var axes = plot.getAxes();
    if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
        pos.y < axes.yaxis.min || pos.y > axes.yaxis.max)
        return;

    var i, j, dataset = plot.getData();
    for (i = 0; i < dataset.length; ++i) {
        var series = dataset[i];

        // find the nearest points, x-wise
        for (j = 0; j < series.data.length; ++j)
            if (series.data[j][0] > pos.x)
                break;
        
        // now interpolate
        var y, p1 = series.data[j - 1], p2 = series.data[j];
        if (p1 == null)
            y = p2[1];
        else if (p2 == null)
            y = p1[1];
        else
            y = parseFloat(parseFloat(p1[1]) + (parseFloat(p2[1]) - parseFloat(p1[1])) * (parseFloat(pos.x) - parseFloat(p1[0])) / (parseFloat(p2[0]) - parseFloat(p1[0])));

       // legends.eq(i).text(series.label.replace(/=.*/, "= " + y.toFixed(2)));
        // alert(y);latestInstaneId
        setEachItemValue(i,latestInstaneId,parseInt(y));
    }
}

function setEachItemValue(index,instanceId,value){
	
	$("#"+index+"_"+instanceId+"_val").html(value);
	
}

function clearEachItemValue(instanceId){
	
	for(var i=0;i<10;i++){
		$("#"+i+"_"+instanceId+"_val").html('');
	}
	
}


function legendItemClick(event) {
	
	var instanceId=event.data.param
    var data = [];
    var datas=datasets[instanceId];
    var choiceContainer = $("#jboss_instance_"+instanceId);
    choiceContainer.find("input:checked").each(function () {
        var key = $(this).attr("name");
        if (key && datas[key])
            data.push(datas[key]);
    });
    if (data.length > 0){
    	$.plot($("#placeholder_"+instanceId),data , options);
    }
       
    
}

function clearReportData(instanceId){
	
	var answer = confirm ("This will delete all data.Are you sure?");
	
	if (answer)
		$.ajax( {
			type :'POST',
			url :'delete_reports',
			data : {
				instanceId :instanceId
			},
			dataType :'json',
			success :function(json) {
				if(json=='OK'){
					
					loadPage();
					
				}else{
					
				    alert("Error while clearing data");
				    
				}
			}
		});		
}

function exportData(instanceId){
	alert("girildi");
	$.ajax( {
		type :'GET',
		url :'export_reports',
		data : {
			instanceId :instanceId
		},
		//dataType :'json',
		success :function(json) {
			
			
		}
	});
}

function getHour(d) {
	var date = d.getHours();
	if (date < 10)
		return "0" + date.toString();
	else
		return date.toString();
}

function getMinute(d) {
	var date = d.getMinutes();
	if (date < 10)
		return "0" + date.toString();
	else
		return date.toString();
}

function getMonth(d) {
	var date = d.getMonth()+1;
	if (date < 10)
		return "0" + date.toString();
	else
		return date.toString();
}

function getDay(d) {
	var date = d.getDate();
	if (date < 10)
		return "0" + date.toString();
	else
		return date.toString();
}
var _tmplCache = {};

/**
 * $("#dyncontent").html(parseTemplate("list", {
				json : json
			}));
 */
function parseTemplate(templateId, data) {

	var err = "";
	var str = '';
	var func;
	$
			.ajax( {
				type : "GET",
				url : "static/"+templateId + ".html",
				async : false,
				success : function(html) {
					str = html;
					try {
						func = _tmplCache[str];
						if (!func) {
							var strFunc = "var p=[],print=function(){p.push.apply(p,arguments);};"
									+ "with(obj){p.push('"
									+ str.replace(/[\r\t\n]/g, " ").replace(
											/'(?=[^#]*#>)/g, "\t").split("'")
											.join("\\'").split("\t").join("'")
											.replace(/<#=(.+?)#>/g, "',$1,'")
											.split("<#").join("');")
											.split("#>").join("p.push('")
									+ "');}return p.join('');";
							func = new Function("obj", strFunc);
							_tmplCache[str] = func;
						}

					} catch (e) {
						err = e.message;
						return "< # ERROR: " + err + " # >";
					}
				}
			});
	return func(data);
};

$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = $.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

function toggleDashPanel(panelId){
	
	if($("#"+panelId+"collapseA").hasClass('collapse')){
		
		$("#"+panelId+"collapseA").removeClass('collapse');
		$("#"+panelId+"collapseA").addClass('collapse2');
		$("#"+panelId+"contentD").hide();
		
	}else{
		
		$("#"+panelId+"collapseA").removeClass('collapse2');
		$("#"+panelId+"collapseA").addClass('collapse');
		$("#"+panelId+"contentD").show();
		
	}
	
}